{{>licenseInfo}}

package {{invokerPackage}};

import io.github.bucket4j.BandwidthBuilder.BandwidthBuilderBuildStage;
import io.github.bucket4j.BandwidthBuilder.BandwidthBuilderCapacityStage;
import org.yaml.snakeyaml.Yaml;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

{{>generatedAnnotation}}
public class Configuration {
    private final Map<String, List<Integer>> rateLimitConfiguration =
            new Yaml().load(this.getClass().getClassLoader().getResourceAsStream("rate-limits.yml"));
    private static Configuration instance;

    private Configuration() {}

    public Function<BandwidthBuilderCapacityStage, BandwidthBuilderBuildStage> getLimit(String operation) {
        return limit ->
                limit.capacity(getValue(operation, 1))
                        .refillGreedy(getValue(operation, 0), Duration.ofSeconds(getValue(operation, 2)));
    }

    private Integer getValue(String operation, Integer position) {
        if (rateLimitConfiguration.containsKey(operation)) {
            if (rateLimitConfiguration.get(operation).size() > position) {
                return rateLimitConfiguration.get(operation).get(position);
            }
        }

        return 1;
    }

    public static Configuration get() {
        if (instance == null) {
            instance = new Configuration();
        }
        return instance;
    }
}